$(function() {
	var pathVar = window.location.search;
	var urlPath = window.location.href;
	var loginStatus = 0;
	if (urlPath.indexOf("s.taobao.com") != -1) { // 商品列表页
		setInterval(function() { // 定时器检测当前URL是否改变

			if (this.urlPath != window.location.search) {
				this.urlPath = window.location.search;
                var itemsId = "";
                $(".pic-link").each(function(i) {// 标签中提取商品ID
                    itemsId += $(this).attr("data-nid") + ","
                });
                itemsId = itemsId.substring(0, itemsId.length - 1);//查询的商品ID
				var itemsArr = Array();
				itemsArr = itemsId.split(",");
				var queryParm = ''; // 查询参数
				$.each(itemsArr,function(i,n){// 处理商品ID，传参给达管家
					queryParm += n+"$"+n+","
				});
				queryParm = queryParm.substring(0,queryParm.length-1);
				// 获取localstorage中登录达管家存储的Cookie
				var darenCookie = '';
                chrome.extension.sendMessage({// 检测当前会话状态
                    "txt": 'darencookie',
                    "type": 'darencookie'
                }, function(response) {
                    try {
						if (response['status'] == 1){
                            darenCookie = response['darencookie'];
                            localStorage.setItem("loginstatus",1);
						}else if(response['status'] == 0){
                            localStorage.setItem("loginstatus",0);
						}
                    } catch (e) {
                        //console.log("Server-Error")
                    }
                });
				if (localStorage.getItem("loginstatus") == 0){
                   console.log('Please sign in.');
				}else{
                    loginStatus = 1;
                    $.ajax({
                        url:"https://www.daren.pro/ProductItemNew/getSearchImgList",// 达管家获取入库列表的接口
                        async:false,
                        type:'POST',
                        dataType:"json",
                        data:{
                            itemid:queryParm
                        }
                    }).then(function(response){
                        if (response['status'] == "success"){
                            darenItems = response['return_Val'];
                            localStorage.setItem("darenItems",darenItems);
                        }
                    },function(e){
                        console.log(e)
                    });
                    darenItems = localStorage.getItem("darenItems");
                    setTimeout(checkStorage(itemsId,darenItems), 200);
				}

			}
		}, 1500)
	}
	if (urlPath.indexOf("item.taobao.com") != -1 || urlPath.indexOf("detail.tmall.com") != -1) { // 商品页
		try {
			if (typeof(g_config) != "undefined") {
				var itemId = g_config["itemId"];
				setTimeout(checkOne(itemId), 500);
			} else {
				var itemId = $("#LineZing").attr("itemid");
				if (typeof(itemId) == "undefined") {
					itemId = $("#service").attr("data-item-id")
				}
				if (typeof(itemId) == "undefined") {
					layer.msg("配置加载出错。")
				} else {
					setTimeout(checkOne(itemId), 500)
				}
			}
		} catch (e) {
			//console.log("Server-Error")
		}
	}

    // 达人登录提取cookie至数据库
    if (urlPath.substring(0, urlPath.length - 1) == "https://we.taobao.com") {
        var cookie = document.cookie;
        var rqInfo = new Object();
        try {
            var nicknname = $("a.J_AppLink").eq(6).next().children().find("span").text();
            if (typeof window.CREATOR_GLOBAL != "undefined") {
                //console.log(window.CREATOR_GLOBAL)
            }
            if (typeof nicknname != "undefined" && nicknname != "") {
                rqInfo["nickname"] = nicknname;
            } else {
                console.log("Not found nickname.");
                return false
            }
            rqInfo["cookie"] = cookie;
            var userId = $("#tb-beacon-aplus").attr("exparams").replace(/[^0-9]/ig, "");// 获取账号ID
            if (userId != undefined) {
                rqInfo["userid"] = userId;
            } else {
                console.log("Got accountId fail");
                return false
            }
            setTimeout(sendCookie2Server(rqInfo), 1000)
        } catch (err) {
            console.log(err)
        }
    }
    // 查询入库
	function checkStorage(itemsId,darenItems) {
		chrome.extension.sendMessage({
			"txt": itemsId,
			"type": 1
		}, function(response) {
			//console.log(response);
			try {
				if (response["errorCode"] == 0) {
					var storageInfo = Object();
					var itemsArr = $.unique(response["data"]);//去重
                    current = [];
                    daguanjia = [];
                    if (darenItems){
                        daguanjia = $.unique(darenItems.split(","));
					}
					storage = [];
                    storage = $.unique(itemsArr.concat(daguanjia));// 合并去重数组
					//console.log(storage);
					current = itemsId.split(",");// 当前页商品ID
					storageInfo.aimo = itemsArr.length;// 艾摩入库数
					storageInfo.guanjia = daguanjia.length;// 达管家入库数
					storageInfo.total = storage.length;// 去重后总入库数
					storageInfo.current = current.length;// 当前页总商品数
					storageInfo.aimorate = (itemsArr.length/current.length).toFixed(2);// 艾摩入库率
                    storageInfo.guanjiarate = (daguanjia.length/current.length).toFixed(2);// 达管家入库率
                    storageInfo.totalrate = (storage.length/current.length).toFixed(2);// 总入库率
					//console.log(JSON.stringify(storageInfo));
					$(".pic-link").each(function() {// 渲染入库的商品
						var itemsId = $(this).attr("data-nid");
						if (isStorage(itemsId, storage)) {
							$(this).parents(".J_PicBox").next().find("strong").append("<b style='font-size:20px;color:#ff0a1c;'>已入库</b>");
							$(this).parents(".J_MouserOnverReq").css("border", "1px solid red");
							// picUlr = "http://localhost/app/store.png";
							// var html = '<img id="tag" src="'+picUlr+'" style="position: relative;float: right;width: 50%;height: 50%;margin-top: -185px;display: block;">';
							// $(this).append(html);
						}
					});
					var layVar = layer.msg("当前页面有 " + storage.length + " 件商品入库");
					layer.style(layVar, {
						width: "150px",
						height: "auto",
						background: "green",
						"font-weight": "bolder"
					})
				}
			} catch (e) {
				console.log(e)
			}
		})
	}
	function checkOne(itemId) {
		console.log(itemId);
		chrome.extension.sendMessage({
			"data": itemId,
			"type": 2
		}, function(response) {
			try {
				if (response["errorCode"] == 0 && response["data"].length >= 1) {
					var layVar = layer.msg("商品已入库", {
						time: 5000,
						offset: "t",
						anim: 6
					});
					layer.style(layVar, {
						width: "150px",
						height: "auto",
						top: "150px",
						background: "green",
						"font-weight": "bolder"
					})
				} else {
					layVar = layer.msg("商品暂未入库", {
						time: 5000,
						offset: "t",
						anim: 6
					});
					layer.style(layVar, {
						width: "150px",
						height: "auto",
						top: "150px",
						background: "green",
						"font-weight": "bolder"
					})
				}
			} catch (e) {
				console.log("Server-Error")
			}
		})
	}
	function isHashChanged() {
		if (this.pathVar != window.location.search) {
			this.pathVar = window.location.search;
			return true
		}
		return false
	}
	function sleep(n) {
		var start = new Date().getTime();
		while (true) {
			if (new Date().getTime() - start > n) {
				break
			}
		}
	}
	function isStorage(itemsId, itemsArr) {
		if ($.inArray(itemsId, itemsArr) != -1) {
			return true
		}
		return false
	}
	// 更新达人Cookie至服务器
    function sendCookie2Server(rqInfo) {
        chrome.extension.sendMessage({
            "data": rqInfo,
            "type": "cookie"
        }, function(response) {
            //console.log(response);
            try {
                if (response["data"] == 1) {
                    layer.msg(response["message"], {
                        offset: "t",
                        anim: 6
                    })
                } else {
                    if (response["data"] == 0 || response["data"] == 2) {
                        if (response["data"] == 2) {
                            console.log(response["message"])
                        } else {
                            console.log(response["message"]);
                            //layVar  = layer.msg('更新成功', {offset: "t",anim: 6});
                            //layer.style(layVar, {width: "150px",height: "auto",top: "150px",background: "blue","font-weight": "bolder"});
                        }
                    } else {
                        console.log("Server-Error-Upload-Fail")
                    }
                }
            } catch (e) {
                console.log(e)
            }
        })
    }
});